import json
from datetime import date

from django.contrib import admin
from django.contrib.auth.models import AbstractUser
from django.db import models


# Create your models here.


class User(AbstractUser):
    nickname = models.CharField('昵称', max_length=255, default="未输入用户名")
    is_admin = models.BooleanField('是否为项目负责人', default=False)

    def get_full_name(self):
        return self.nickname

    def get_performamce(self, project_id):
        try:
            performance = Performance.objects.get(user_id=self.id, project_id=project_id)
            return performance.get_true_num()
        except:
            return 0

    def get_achievement(self, project_id):
        try:
            performance = Achievement.objects.get(user_id=self.id, project_id=project_id)
            return performance.get_true_num()
        except:
            return 0

    def get_argument(self, project_id):
        try:
            performance = Argument.objects.get(user_id=self.id, project_id=project_id)
            return performance.get_total_argument()
        except:
            return 0

    def get_service(self):
        try:
            service = Service.objects.get(user_id=self.id)
            return service.get_total_service()
        except:
            return 0

    def get_research(self):
        try:
            service = Research.objects.get(user_id=self.id)
            return service.get_total_research()
        except:
            return 0

    def get_related_users(self):
        try:
            projects = Project.objects.all().filter(head_user_id=self.id)
            tmp = []
            for item in projects:
                p = Performance.objects.all().filter(project_id=item.id)
                for item1 in p:
                    tmp.append(item1.user)
                a = Achievement.objects.all().filter(project_id=item.id)
                for item2 in a:
                    tmp.append(item2.user)
            return list(set(tmp))
        except:
            return []


class Project(models.Model):
    """
    项目信息
    """
    serial = models.CharField('项目编号', max_length=255)
    decree = models.CharField('项目令号', max_length=255, default='')
    title = models.CharField('项目标题', max_length=255)
    introduce = models.TextField('简介')
    head_user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='负责人'
    )
    total_number = models.FloatField('资金总数')
    start_date = models.DateField('开始日期')
    end_date = models.DateField('结束日期')
    is_active = models.BooleanField('是否有效', default=True)
    status = models.IntegerField('项目状态( 0 申报，1 立项，2 合同已签，3 中期，4 已结题)', default=0)
    score = models.FloatField('项目绩点', default=0)

    def to_json(self):
        return {
            "project_id": self.id,
            "serial": self.serial,
            "decree": self.decree,
            "title": self.title,
            "introduce": self.introduce,
            "head_user_id": self.head_user.id,
            "head_user": self.head_user.username,
            "total_number": self.total_number,
            "start_date": self.start_date.strftime("%Y-%m-%d"),
            "end_date": self.end_date.strftime("%Y-%m-%d"),
        }

    def head_user_info(self):
        user = User.objects.get(id=self.head_user)
        return user.last_name + user.first_name

    class Meta:
        verbose_name = '项目'
        verbose_name_plural = '项目'

    def __str__(self):
        return self.title

    def get_user_list(self):
        try:
            tmp = []
            p = Performance.objects.all().filter(project_id=self.id)
            for item1 in p:
                tmp.append(item1.user)
            a = Achievement.objects.all().filter(project_id=self.id)
            for item2 in a:
                tmp.append(item2.user)
            return list(set(tmp))
        except:
            return []


class Performance(models.Model):
    """
    项目绩效第一项
    """
    project = models.ForeignKey(
        Project,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='项目'
    )
    user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='参与人员'
    )
    type = models.IntegerField()
    is_active = models.BooleanField(default=True)
    number = models.FloatField()

    def user_name(self):
        user = User.objects.get(id=self.user_id)
        return user.last_name + user.first_name

    def project_info(self):
        project = Project.objects.get(id=self.project_id)
        return project.title

    def get_true_num(self):
        if self.type == 2:
            return self.number
        else:
            return self.number * self.project.total_number


class Achievement(models.Model):
    """
    项目绩效第二项
    """
    project = models.ForeignKey(
        Project,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='项目'
    )
    user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='参与人员'
    )
    type = models.IntegerField()
    number = models.FloatField()
    is_active = models.BooleanField(default=True)

    def user_name(self):
        user = User.objects.get(id=self.user_id)
        return user.last_name + user.first_name

    def project_info(self):
        project = Project.objects.get(id=self.project_id)
        return project.title

    def get_true_num(self):
        if self.type == 2:
            return self.number
        else:
            return self.number * self.project.total_number


class Argument(models.Model):
    """
    论证编制
    """
    user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='参与人员'
    )

    project = models.ForeignKey(
        Project,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='项目'
    )

    guide = models.CharField("指南编制", max_length=255)
    standard = models.CharField("标准编制", max_length=255)
    application = models.CharField("项目申报", max_length=255)
    total_num = models.FloatField("绩效总数", default=0)

    def get_guide_result(self):
        try:
            result = 0
            data = json.loads(self.guide)
            for item in data:
                result += float(item.get('level')) * 10 / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_standard_result(self):
        try:
            result = 0
            data = json.loads(self.standard)
            for item in data:
                result += float(item.get('level')) * 10 / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_application_result(self):
        try:
            result = 0
            data = json.loads(self.application)
            for item in data:
                if float(item.get('money')) * float(item.get('ratio')) > 100:
                    tmp = 100
                else:
                    tmp = float(item.get('money')) * float(item.get('ratio'))
                result += tmp * float(item.get('level')) / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_total_argument(self):
        return self.get_guide_result() + self.get_standard_result() + self.get_application_result()


class Service(models.Model):
    """
    公共服务
    """
    user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='参与人员'
    )

    activity = models.CharField("活动参展", max_length=255)
    hangar = models.CharField("机库讲解", max_length=255)
    visual_design = models.CharField("视觉设计", max_length=255)
    service = models.CharField("综合服务", max_length=255)
    total_num = models.FloatField("绩效总数", default=0)

    def get_activity_result(self):
        try:
            result = 0
            data = json.loads(self.activity)
            for item in data:
                result += float(item.get('level')) * 10 / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_hangar_result(self):
        try:
            result = 0
            data = json.loads(self.hangar)
            for item in data:
                result += float(item.get('level')) * 0.5 / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_visual_design_result(self):
        try:
            result = 0
            data = json.loads(self.visual_design)
            for item in data:
                result += float(item.get('level')) * 0.5 / float(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_service_result(self):
        try:
            result = 0
            data = json.loads(self.service)
            for item in data:
                print(item.get('overall'), item.get('intensity'))
                result += float(item.get('overall')) * 4 * float(item.get('intensity'))
            return round(result, 2)
        except:
            return 0

    def get_total_service(self):
        return self.get_activity_result() + self.get_hangar_result() + \
               self.get_visual_design_result() + self.get_service_result()


class Research(models.Model):
    """
    科研成果
    """
    user = models.ForeignKey(
        User,
        models.SET_NULL,
        blank=True, null=True,
        verbose_name='参与人员'
    )

    paper = models.CharField("论文", max_length=255)
    patent = models.CharField("专利", max_length=255)
    award = models.CharField("奖项", max_length=255)
    acceptance = models.CharField("解题验收", max_length=255)
    total_num = models.FloatField("绩效总数", default=0)

    def get_paper_result(self):
        try:
            result = 0
            data = json.loads(self.paper)
            print(type(data), len(data))
            for item in data:
                # print(type(item))
                # print(int(item.get('rank')) * int(item.get('partition')) * 5 / int(item.get('total_people')))
                # print("-----")
                # print(int(item.get('total_people')))
                result = result + float(item.get('rank')) * float(item.get('partition')) * 5 / int(
                    item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_patent_result(self):
        try:
            result = 0
            data = json.loads(self.patent)
            for item in data:
                result = result + float(item.get('rank')) * 2 / int(item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_award_result(self):
        try:
            result = 0
            data = json.loads(self.award)
            for item in data:
                result = result + float(item.get('level')) * float(item.get('rank')) * 30 / int(
                    item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_acceptance_result(self):
        try:
            result = 0
            data = json.loads(self.acceptance)
            for item in data:
                result = result + float(item.get('level')) * float(item.get('rank')) * 30 / int(
                    item.get('total_people'))
            return round(result, 2)
        except:
            return 0

    def get_total_research(self):

        print('====', json.loads(self.paper), self.get_paper_result())
        print('====', json.loads(self.patent), self.get_patent_result())
        print('====', json.loads(self.award), self.get_award_result())
        print('====', json.loads(self.acceptance), self.get_acceptance_result())

        return self.get_paper_result() + self.get_patent_result() + \
               self.get_award_result() + self.get_acceptance_result()
